package appapi.service.impl;

import appapi.Global.BusinessException;
import appapi.Request.InspectionPageReq;
import appapi.Vo.AppVo.AppRectRecVo;
import appapi.Vo.AppVo.AppRectVo;
import appapi.Vo.EquipmentsExportVo;
import appapi.dao.AnnexMapper;
import appapi.dao.RectdetailMapper;
import appapi.dao.RectificationMapper;
import appapi.dao.StaffMapper;
import appapi.dto.*;
import appapi.entity.Zhongjiao.AnnexDto;
import appapi.entity.Zhongjiao.RectdetailEntity;
import appapi.entity.Zhongjiao.RectificationDto;
import appapi.entity.app.AnnexEntity;
import appapi.entity.app.RectificationEntity;
import appapi.entity.basic.UserInfo;
import appapi.entity.bridge.vo.RectificationCreateTimeCount;
import appapi.entity.bridge.vo.RectificationUpdateTimeCount;
import appapi.service.IRectificationService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author djq
 * @date 2023/5/22 15:21
 * @description:
 */
@Component
public class RectificationServiceImpl implements IRectificationService {
    @Resource
    private RectificationMapper rectificationMapper;
    @Resource
    private RectdetailMapper rectdetailMapper;
    @Resource
    private AnnexMapper annexMapper;
    @Resource
    StaffMapper staffMapper;

    @Override
    public List<Map<String, Object>> SelectRectificationPage(UserInfo userInfo, InspectionPageReq dto) {
        //如果什么都没传,则查到该账号的所属机构显示数据
            if (dto.getOrgaPathIds()==null) {
            //拿到人员信息
            Map<String, Object> staffDto = staffMapper.selectStaffDetail(userInfo.getUserid());
            String orgaPathIds = staffDto.get("orgaPathIds").toString();
            dto.setOrgaPathIds(orgaPathIds);
        }

        PageHelper.startPage(dto.getCurrPage(), dto.getPageSize());
        return rectificationMapper.selectRectificationPage(dto);
    }

    @Override
    public List<Map<String, Object>> SelectRectificationList(Long equipId) {
        return rectificationMapper.selectRectificationList(equipId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void InsertRectification(AddRectifDto dto) {
        RectificationDto rectDto = new RectificationDto();
        List<String> items = dto.getRectDetails().stream().map(AddRectDetailDto::getRectItem).collect(Collectors.toList());
        BeanUtils.copyProperties(dto, rectDto);
        rectDto.setRectType(0);
        rectDto.setRectItem(String.join(",", items));
        //此处存入人员id
        rectDto.setRectSource(dto.getOperId().longValue());
        rectDto.setRectState(0);
        rectDto.setRectAdd(0);
        rectDto.setAuditState(0);
        rectDto.setCreateTime(LocalDateTime.now());
        rectDto.setUpdateTime(LocalDateTime.now());
        rectDto.setOperId(dto.getOperName());
        if(rectificationMapper.insertSelective(rectDto)==0){
            throw new BusinessException(500,"新增失败");
        }


        List<RectdetailEntity> details = dto.getRectDetails().stream().map(item -> {
            RectdetailEntity entity = new RectdetailEntity();
            BeanUtils.copyProperties(item, entity);
            entity.setImgUrl(String.join(",", item.getImgUrls()));
            entity.setCreateTime(LocalDateTime.now());
            entity.setUpdateTime(LocalDateTime.now());
            entity.setAuditState(0);
            entity.setRectId(rectDto.getRectId());
            return entity;
        }).collect(Collectors.toList());

        if (dto.getRectDetails()!=null&&dto.getRectDetails().size()>0) {
            rectdetailMapper.insertList(details);
        }

        //有附件则新增附件
        if (dto.getAnnexUrl().size() > 0) {
            //String[] user = JwtUtil.getUserInfoByJwtToken(request);
            List<AnnexEntity> annexCollect = dto.getAnnexUrl().stream().map(annex -> {
                AnnexEntity entity = new AnnexEntity();
                entity.setCreateTime(LocalDateTime.now());
                entity.setUpdateTime(LocalDateTime.now());
                entity.setAnnexTitle("整改");
                entity.setAnnexType(AnnexType.AnnexTypeEnum.rectification.name());
                entity.setAnnexUrl(annex);
                entity.setCreateUser(dto.getOperName());
                entity.setRecId(rectDto.getRectId());
                return entity;
            }).collect(Collectors.toList());

            annexMapper.insertList(annexCollect);
        }



    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void UpdateRectification(UpdateRectifDto updateRectifDto) {
        RectificationDto dto = new RectificationDto();
        BeanUtils.copyProperties(updateRectifDto, dto);


        List<String> items = updateRectifDto.getRectDetails().stream().map(AddRectDetailDto::getRectItem).collect(Collectors.toList());
        dto.setRectType(0);
        dto.setRectItem(String.join(",", items));
        dto.setRectAdd(0);
        dto.setCreateTime(LocalDateTime.now());
        dto.setUpdateTime(LocalDateTime.now());
        dto.setOperId(dto.getOperName());
        rectificationMapper.updateByPrimaryKeySelective(dto);

        rectdetailMapper.deleteByRectId(dto.getRectId());


        List<RectdetailEntity> details = updateRectifDto.getRectDetails().stream().map(item -> {
            RectdetailEntity entity = new RectdetailEntity();
            BeanUtils.copyProperties(item, entity);
            entity.setImgUrl(item.getImgUrls()==null?"":String.join(",", item.getImgUrls()));
            entity.setHandleImges(item.getHandleImages()==null?"":String.join(",", item.getHandleImages()));
            entity.setCreateTime(LocalDateTime.now());
            entity.setUpdateTime(LocalDateTime.now());
            entity.setRectId(dto.getRectId());
            return entity;
        }).collect(Collectors.toList());

        rectdetailMapper.insertList(details);

        //有附件则新增附件
        if (updateRectifDto.getAnnexUrl().size() > 0) {
            //String[] user = JwtUtil.getUserInfoByJwtToken(request);
            List<AnnexEntity> annexCollect = updateRectifDto.getAnnexUrl().stream().map(annex -> {
                AnnexEntity entity = new AnnexEntity();
                entity.setCreateTime(LocalDateTime.now());
                entity.setUpdateTime(LocalDateTime.now());
                entity.setAnnexTitle("整改");
                entity.setAnnexType(AnnexType.AnnexTypeEnum.rectification.name());
                entity.setAnnexUrl(annex);
                entity.setCreateUser(updateRectifDto.getOperName());
                entity.setRecId(dto.getRectId());
                return entity;
            }).collect(Collectors.toList());

            annexMapper.insertList(annexCollect);
        }

    }

    @Override
    public void DelRectification(Long rectId) {
        rectificationMapper.deleteByPrimaryKey(rectId);
    }

    @Override
    public int InsertBatch(List<RectificationEntity> rectificationEntityList) {
        return rectificationMapper.insertBatch(rectificationEntityList);
    }

    @Override
    public int DeleteBatch(Integer rectType, List<Long> sourceIds) {
        return rectificationMapper.deleteBatch(rectType, sourceIds);
    }

    @Override
    public int DeleteByRecId(Integer rectType, Long recId) {
        return rectificationMapper.deleteByRecId(rectType, recId);
    }

    @Override
    public AppRectVo selectRectDetail(GetRectfiDetailDto dto) {
        AppRectVo vo = new AppRectVo();
        //查到记录
        RectificationDto rectificationDto = rectificationMapper.selectWithEquipByPrimaryKey(dto.getRecordId());

        BeanUtils.copyProperties(rectificationDto,vo);
        vo.setOperName(rectificationDto.getOperId());
        //查到详情
        List<RectdetailEntity> rectDetails = rectdetailMapper.selectByRectId(dto.getRecordId());

        List<AppRectRecVo> collect = rectDetails.stream().map(detail -> {
            AppRectRecVo appRectRecVo = new AppRectRecVo();
            BeanUtils.copyProperties(detail, appRectRecVo);
            appRectRecVo.setImgUrlList(detail.getImgUrl()==null?new ArrayList<>():Arrays.asList(detail.getImgUrl().split(",")));
            appRectRecVo.setHandleImgeList(detail.getHandleImges()==null?new ArrayList<>():Arrays.asList(detail.getHandleImges().split(",")));
            return appRectRecVo;
        }).collect(Collectors.toList());

        vo.setRectRecDetails(collect);

        //查到附件
        List<AnnexDto> annexDtos = annexMapper.selectAllByRecId(AnnexType.AnnexTypeEnum.rectification.name(), dto.getRecordId());

        vo.setAnnexUrl(annexDtos.stream().map(AnnexDto::getAnnexUrl).collect(Collectors.toList()));

        return vo;
    }

    @Override
    public void UpdateRectificationAudit(RectAuditDto updateDto) {
        RectificationDto dto = new RectificationDto();

        BeanUtils.copyProperties(updateDto,dto);
        if( rectificationMapper.updateByPrimaryKeySelective(dto)==0){
            throw new BusinessException(500,"更新状态失败!");
        }

    }

    @Override
    public List<EquipmentsExportVo> getList(InspectionPageReq req) {
        List<EquipmentsExportVo> list = rectificationMapper.RectificationRecExport(req);
        return list;
    }

    @Override
    public Map<String,Object> getCompareData(Long orgaId) {
//        Long orgaId=13L;
        List<RectificationCreateTimeCount>list1=new ArrayList<>();
        List<RectificationUpdateTimeCount>list2=new ArrayList<>();
        java.time.LocalDate now = java.time.LocalDate.now();
        for (int i = 12; i >0 ; i--) {
            LocalDate date = now.plusMonths(-i);
            String str = date.toString();
            Integer count = rectificationMapper.getCreateTimeData(str.substring(0, 7),orgaId);
            Integer updateTimeData = rectificationMapper.getUpdateTimeData(str.substring(0, 7),orgaId);
            RectificationCreateTimeCount rectificationCompareCount = new RectificationCreateTimeCount(str.substring(0, 7),count);
            list1.add(rectificationCompareCount);
            RectificationUpdateTimeCount rectificationUpdateTimeCount = new RectificationUpdateTimeCount(str.substring(0, 7),updateTimeData);
            list2.add(rectificationUpdateTimeCount);
        }
        Map<String,Object> map=new HashMap<>();
        map.put("before",list1);
        map.put("after",list2);
        return map;
    }

}
